<template>
    <el-dialog title="定价单" :visible.sync="FixPriceDialog" @close="handleClose()" width="60rem" class="dialog">
        <template slot="title">
            <span
                style="color: rgba(52, 69, 99, 1); font-size: 18px;font-weight: bold; margin-left: 5px;margin-top: 34px;">定价单</span>
            <br /><br />
            <hr />
        </template>
        <div class="dialog-content">
            <el-form ref="form">
                <el-form-item label="定价商品" label-width="90px">
                    <el-link style="float:right;" type="primary" @click="addProduct()"
                        :underline="false">+商品</el-link>
                </el-form-item>
                <div v-for="(tag, index) in tags" :key="tag.commodityName" class="productTable">
                    <el-tag closable @close="() => deleteProduct(index)">
                        {{ tag.commodityName }}
                    </el-tag>
                    <el-table :data="[tag.details]" border>
                        <el-table-column v-for="(label, key) in tableColumns" :key="key" :prop="key" :label="label"
                        min-width="100"></el-table-column>
                        <el-table-column prop="priceType" label="定价类型" width="129" :resizable="false">
                            <el-select v-model="tag.details.priceType" placeholder="请选择">
                                <el-option v-for="item in optionsPriceType" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-table-column>
                        <el-table-column prop="price" label="零售价" width="129" :resizable="false">
                            <template slot-scope="{}" v-if="tag.details.priceType == '1'">
                                <el-input v-model="tag.details.price">
                                    <template #prefix>￥</template>
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="priceUnit" label="价格单位" width="129"
                            :resizable="false">
                            <div  v-if="tag.details.priceType == '1'">
                                <el-select v-model="tag.details.priceUnit">
                                    <el-option v-for="item in optionsPriceUnit" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                        </el-table-column>
                        <el-table-column prop="inventoryProcessing" label="库存处理" width="129"
                            :resizable="false">
                            <el-select v-model="tag.details.inventoryProcessing" placeholder="请选择" >
                                <el-option v-for="item in optionsInventoryProcessing" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
            <AddProduct :dialogVisible.sync="visible" @updateTags="updateTags"></AddProduct>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="info" @click="FixPriceDialog = false" class="footer-button">
                取消
            </el-button>
            <el-button @click="submitPricing" class="footer-button confirm-button">
                确定
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
import { setPrice } from '@/api/api.js'
import AddProduct from '@/components/AddProduct.vue'
export default {
    components: {
        AddProduct
    },
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        },
    },
    computed: {
    tableColumns() {
      if (this.tags.length > 0 && this.tags[0].details) {
        const keysToExclude = ['priceType', 'price', 'priceUnit', 'inventoryProcessing'];
        return Object.keys(this.tags[0].details).reduce((columns, key) => {
          if (!keysToExclude.includes(key)) {
            columns[key] = key; 
          }
          return columns;
        }, {});
      }
      return {};
    }
  },
    data() {
        return {
            FixPriceDialog: this.dialogVisible,
            addProductVisible: false,
            tags: [],
            visible: false,
            formLabelWidth: '120px',
            optionsPriceType: [{
                value: 1,
                label: '固定价格'
            },{
                value: 2,
                label: '面议'
            }],
            optionsPriceUnit: [{
                value: 1,
                label: '元'
            },{
                value: 2,
                label: '千元'
            },{
                value: 3,
                label: '万元'
            }],
            optionsInventoryProcessing: [{
                value: 1,
                label: '自动出库'
            },{
                value: 2,
                label: '不计库存'
            }],
        }
    },
    methods: {
        handleClose() {
            this.$emit('update:dialogVisible', false); // 发送事件以更新父组件的 prop
            this.tags=[];
        },
        addProduct() {
            this.visible = true;
        },
        updateTags(newTags) {
            this.tags = newTags;
        },
        deleteProduct(index) {
            this.tags.splice(index, 1);
        },
        watchPriceType(tag, index) {
            this.$watch(
                () => tag.details.priceType,
                (newValue, oldValue) => {
                    // console.log(`priceType changed for tag ${tag.name}: ${newValue}`);
                }
            );
        },
        async submitPricing(){
            console.log("添加定价单确定")
            console.log(this.tags)
            const formDataList = this.tags.map(tag => ({
                addSkuDTOList: [{
                    fixPrice: tag.details.priceType == '1'? Number(tag.details.price) : 0,
                    fixPriceType: tag.details.priceType,
                    priceUnit: tag.details.priceType == '1'? tag.details.priceUnit : '',
                    skuCode: tag.skucode,
                    stockType: tag.details.inventoryProcessing
                }],
                commodityId: tag.id,
                remark: "1",
                shopId: sessionStorage.getItem('shopid'),  // 商铺id
            }));
            console.log("提交表单数据:", JSON.stringify(formDataList, null, 2));
            try{
                const response = await setPrice(formDataList);
                console.log("提交成功:", response);
                if(response.data.code == 200){
                    this.$message({
                        type:'success',
                        message: response.data.result
                    });
                    this.handleClose();
                    // 发出 reloadData 事件
                    this.$emit('reloadData');
                }
            }catch(error){
                console.error("提交失败:", error);
            }
        }
    },
    mounted() {
        this.tags.forEach((tag, index) => {
            this.watchPriceType(tag, index);
        });
    },
    watch: {
        dialogVisible(newVal) {
            this.FixPriceDialog = newVal;
        },
        tags: {
            handler(newTags) {
                newTags.forEach((tag, index) => {
                    this.watchPriceType(tag, index);
                });
            },
            deep: true,
            immediate: true
        }
    },
}
</script>

<style scoped>
.dialog {
    max-height: 100vh !important;
    overflow-y: hidden;
    left: 15%;
}

.dialog-content {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    height: 480px;
}

.el-icon-search {
    margin-top: 14px;
    width: 15px;
    margin-left: 6px;
}

.el-pagination {
    float: right;
}

.dialog-footer {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    background-color: #fff;
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
}

.footer-button {
    font-size: 14px;
    height: 38px;
    width: 150px;
    margin-right: 8px;
}

.confirm-button {
    background-color: rgba(90, 52, 179, 1);
    color: white;
}
</style>
